package com.flkin.modules.system.service.impl;

import com.flkin.modules.system.domain.User;
import com.flkin.modules.system.repository.UserRepository;
import com.flkin.modules.system.service.UserService;
import com.flkin.modules.system.service.dto.UserDto;
import com.flkin.modules.system.service.mapstruct.UserMapper;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author yanxiang.huang 2020-12-07 22:38:02
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository userRepository;
    @Resource
    private UserMapper userMapper;

    @Override
    public List<UserDto> getAll() {
        return userMapper.toDto(userRepository.findAll());
    }

    @Override
    public UserDto findById(Long id) {
        User user = userRepository.findById(id).orElse(null);
        if (user != null) {
            return userMapper.toDto(user);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserDto create(User resource) {
        return userMapper.toDto(userRepository.save(resource));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(User resource) {
        userRepository.save(resource);
    }

    @Override
    public void deleteAll(List<Long> ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }

    @Override
    public void deleteById(Long id) {
        userRepository.deleteById(id);
    }

    @Override
    public User findByName(String username) {
        User user = new User();
        user.setUsername(username);
        return userRepository.findOne(Example.of(user)).orElse(null);
    }
}
